package com.heitian.ssm.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


public class JsonResultUtils {

    public static void ajaxReturn(HttpServletResponse response, String jsonString) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json");
        try {
            PrintWriter out = response.getWriter();
            out.print(jsonString);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void ajaxReturnJsonP(HttpServletRequest request, HttpServletResponse response, Object o) {
        response.setCharacterEncoding("UTF-8");
        try {
            String jsonString = FastJsonUtils.toJSONString(o);
            String callback = request.getParameter("callback");
            StringBuilder resBuilder = new StringBuilder();
            if (StringUtils.isBlank(callback)) {
                response.setContentType("text/json");
                resBuilder.append(jsonString);

            } else {
                response.setContentType("text/javascript");
                resBuilder.append(callback).append("(").append(jsonString).append(")");
            }
            PrintWriter out = response.getWriter();
            out.print(resBuilder.toString());
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void ajaxReturnJsonPJson(HttpServletRequest request, HttpServletResponse response, String jsonString) {
        response.setCharacterEncoding("UTF-8");
        try {
            String callback = request.getParameter("callback");
            StringBuilder resBuilder = new StringBuilder();
            if (StringUtils.isBlank(callback)) {
                response.setContentType("text/json");
                resBuilder.append(jsonString);

            } else {
                response.setContentType("text/javascript");
                resBuilder.append(callback).append("(").append(jsonString).append(")");
            }
            PrintWriter out = response.getWriter();
            out.print(resBuilder.toString());
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
